﻿Imports System.Data
Imports System.Text

Imports System.ComponentModel 
Imports System.Collections.ObjectModel  



Public Class CSServiciosGenerales



   Private pLstError As Dictionary(Of integer, CError)

    Public Function ModificarFechaBSO(ByVal fecha As Date) As Boolean
        Dim sMsgError As String = ""
        If CFLServicioLocalSQLServerDB.ModificarFechaBSO(fecha, sMsgError) = False Then
           Throw New Exception(sMsgError)
        End If
        Return True
    End Function

    Public Function CancelarFechaBSO(ByVal fecha As Date) As Boolean
        Dim sMsgError As String = ""
        If CFLServicioLocalSQLServerDB.CancelarFechaBSO(fecha, sMsgError) = False Then
           Throw New Exception(sMsgError)
        End If
        Return True
    End Function

    Public Function CargarFechasDecalog(ByVal fechaInicio As Date, ByVal fechaFin As Date) As Boolean
        Dim sMsgError As String = ""
            Dim dtDatos As DataTable = CFLServiciosMacrosSyBaseDB.ObtieneFechasInhabiles(fechaInicio, fechaFin)
            If dtDatos.Rows.Count > 0 Then
                If CFLServicioLocalSQLServerDB.CargarFechasDecalog(dtDatos, fechaInicio, fechaFin, sMsgError) = False Then
                   Throw New Exception(sMsgError)
                End If
            End If
        
        Return True
    End Function

    Public Function ObtieneCatalogo(ByVal IdCat As Integer) As List(Of CTCatalogoGenerico)
        Try
            Dim lstCatalogo As New List(Of CTCatalogoGenerico)
            Dim dtDatos      As DataTable = CFLServicioLocalSQLServerDB.ObtieneCatalogo(IdCat)
            Dim c            As CTCatalogoGenerico

            If dtDatos.Rows.Count > 0 Then
                For Each dt As DataRow In dtDatos.Rows
                    c = New CTCatalogoGenerico()
                    With c       
                        .IdCat             = Convert.ToInt32(dt("ID_CAT"))
                        .Clave             = Convert.ToInt32(dt("CLAVE"))
                        .Valor             = Convert.ToString(dt("VALOR"))
                        .Descripcion       = Convert.ToString(dt("DESCRIPCION"))
                        .FechaAlta         = Convert.ToDateTime(dt("FEC_ALTA"))
                        .FechaMod          = Convert.ToDateTime(dt("FEC_MOD"))
                        .FechaBaja         = Convert.ToDateTime(dt("FEC_BAJA"))
                    End With
                    lstCatalogo.Add(c)
                    c = Nothing
                Next
            End If

            Return lstCatalogo
        Catch ex As Exception                
            Throw ex
        End Try
    End Function

    Public Sub ObtienePartidasSolicitud()
        Try
            Dim lstPartidas As New List(Of CTPartidaSolicitud)
            Dim dtDatos As DataTable = CFLServicioLocalSQLServerDB.ObtienePartidasSolicitud(BSO.BSOId)
            Dim ps As CTPartidaSolicitud

            If dtDatos.Rows.Count > 0 Then
                For Each dt As DataRow In dtDatos.Rows
                    ps = New CTPartidaSolicitud()
                    With ps
                        .PartidaSolId = Convert.ToInt32(dt("ID_PARTIDA_PS"))
                        .EstatusActualPS = Convert.ToInt32(dt("ESTATUS_PARTIDA"))
                        .CantidadActualPS = Convert.ToDecimal(dt("CANTIDAD_ACTUAL"))
                        .SecSol = Convert.ToInt32(dt("SEC_PARTIDA"))
                        .TvngId = Convert.ToInt32(dt("TVNG"))
                        .FecSol = Convert.ToDateTime(dt("FEC_SOLICITUD"))
                        .FecLiq = Convert.ToDateTime(dt("FEC_LIQUIDACION"))
                        .FecPlazo = Convert.ToDateTime(dt("FEC_PLAZO"))
                        .CantidadSol = Convert.ToDecimal(dt("CANTIDAD_SOL"))
                        .Comentarios = Convert.ToString(dt("COMENTARIO"))
                        .TipoCantidadId = Convert.ToInt32(dt("TIPO_CANTIDAD"))
                        .Plazo = Convert.ToInt32(dt("PLAZO"))
                        .Estatus = Convert.ToString(dt("ESTATUS_VALOR"))
                        .Tvng = Convert.ToString(dt("TV_VALOR"))
                        .IntermFlexibles = Convert.ToInt32(dt("INTER_FLEXIBLES"))
                        .FolioEnviadoDecalog = Convert.ToInt32(dt("FOLIO_ENVIADO_DECALOG"))
                    End With
                    lstPartidas.Add(ps)
                    ps = Nothing
                Next
            End If
            BSO.LstPS = lstPartidas
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Public Sub ObtienePartidasAjuste()
        Try
            Dim lstPartidas As New List(Of CTPartidaAjuste)
            Dim dtDatos As DataTable = CFLServicioLocalSQLServerDB.ObtienePartidasAjuste(BSO.BSOId)
            Dim pa As CTPartidaAjuste
            Dim pEjecucuion As CTPartidaEJ
            If dtDatos.Rows.Count > 0 Then
                For Each dt As DataRow In dtDatos.Rows
                    pa = New CTPartidaAjuste()
                    With pa
                        .PartidaAjusteID = Convert.ToInt32(dt("ID_PARTIDA_AJUSTE"))
                        .PartidaSolicitudId = Convert.ToInt32(dt("ID_PARTIDA_PS"))
                        .PartidaEJId =   dT("ID_PARTIDA_EJ") 'RIRI
                        .TipoCantidadId = Convert.ToInt32(dt("ID_TIPO_CANTIDAD"))
                        .CantidadAjus = Convert.ToDecimal(dt("CANTIDAD_AJUS"))
                        .FecCreacion = Convert.ToDateTime(dt("FEC_CREACION"))
                        .FecAplicacion = Convert.ToDateTime(dt("FEC_APLICACION"))
                        .Comentario = Convert.ToString(dt("COMENTARIO"))
                        .Estatus = Convert.ToInt32(dt("ESTATUS"))
                        .EstatusValor = Convert.ToString(dt("ESTATUS_VALOR"))
                    End With
                    pEjecucuion = BSO.LstPEJ.Find(Function(x) x.PartidaEJId = pa.PartidaEJId)
                    pEjecucuion.LstPAJ.Add(pa)
                    BSO.LstPAJ.Add(pa)
                    pa = Nothing
                Next
            End If
            
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Public Function CargarBSOActual() As Boolean
        Try
            Dim dtDatos As DataTable = CFLServicioLocalSQLServerDB.ObtieneBSOActivo()

            If dtDatos.Rows.Count > 0 Then
                For Each dt As DataRow In dtDatos.Rows
                    BSO.BSOId = Convert.ToInt16(dt("ID_BSO"))
                    BSO.SecBSO = Convert.ToInt16(dt("SEC_BSO"))
                    BSO.EstatusBSOID = Convert.ToInt16(dt("ESTATUS_BSO"))
                    BSO.FecOperacion = DateTime.Parse(Convert.ToDateTime(dt("FEC_OPERA")).ToString("dd/MM/yyyy"))
                    BSO.FecCreacion = Convert.ToDateTime(dt("FEC_CREACION"))
                    BSO.UsuGestor = Convert.ToInt16(dt("USU_GESTOR"))
                Next                                              

                BSO.LstPAJ.Clear() 'RIRI
                BSO.LstPEJ.Clear() 'RIRI
                ObtienePartidasSolicitud()
                CargarPartidasEjecucionEnBSO () 'RIRI
                ObtienePartidasAjuste()
            Else
                BSO.BSOId = Nothing
                BSO.SecBSO = Nothing
                BSO.EstatusBSOID = CTBSO.enumEstatusBSO.NO_CREADA
                BSO.FecOperacion = ObtieneFechaParamBSO()
                BSO.FecCreacion = Date.Now
                BSO.UsuGestor = Nothing
                BSO.LstPS = New List(Of CTPartidaSolicitud)
                BSO.LstPAJ = New List(Of CTPartidaAjuste)

            End If
            
            Return True
        Catch ex As Exception
            Throw ex
        End Try
    End Function

    Public Function CancelarPA(ByVal idPartidaAjuste As Integer, ByRef estatus As String) As Boolean
        Dim sMsgError As String = ""
        If CFLServicioLocalSQLServerDB.ActualizaEstatusPA(idPartidaAjuste, CTPartidaAjuste.enumEstatusPAJ.CANCELADA, sMsgError) = False Then
           Throw New Exception(sMsgError)
        End If
        Return True
    End Function

    Public Function CancelarPS(ByVal idPartida As Integer) As Boolean
        Dim sMsgError As String = ""
        If CFLServicioLocalSQLServerDB.CancelarPAsPorPartidaSol(idPartida, CTPartidaSolicitud.enumEstatusPS.CANCELADA, sMsgError) = True Then
            Return True
        Else
           Throw New Exception(sMsgError)
        End If

    End Function

    Public Function EnviarPS(ByVal idPartida As Integer) As Boolean
        Dim sMsgError As String = ""
        If CFLServicioLocalSQLServerDB.ActualizaEstatusPS(idPartida, CTPartidaSolicitud.enumEstatusPS.ENVIADA, "", sMsgError) = True Then
            Return True
        Else
           Throw New Exception(sMsgError)
        End If

    End Function

    Public Function EnviarPA(ByVal idPartida As Integer) As Boolean
        Dim sMsgError As String = ""
        If CFLServicioLocalSQLServerDB.ActualizaEstatusPA(idPartida, CTPartidaAjuste.enumEstatusPAJ.ENVIADA, sMsgError) = True Then
            Return True
        Else
           Throw New Exception(sMsgError)
        End If

    End Function

    Public Function ObtieneFechaParamBSO() As Date
        Try
            Dim fecha = CServicioLocalSQLServerDB.ObtenerParametro(57)
            Return (DateTime.Parse(fecha & " " & Date.Now.ToString("hh:mm:ss")))
        Catch ex As Exception
            Throw ex
        End Try
        
    End Function

    Public Function CrearBSO(ByRef eventoBit As CSBitEvento) As Boolean
        Dim sMsgError As String = ""
        Try
            Dim folio As Integer = CFLServicioLocalSQLServerDB.ObtieneFolio("ID_BSO","FL_OP_BSO")
            BSO.BSOId = folio
            eventoBit.GuadarDetalle("Folio idBSO", folio)
            If CFLServicioLocalSQLServerDB.CrearBSO(sMsgError) = True Then
                Return True
            Else
               Dim errorBit = eventoBit.GuardarError("Error al crear BSO: " & sMsgError)
               Throw New Exception(sMsgError & " -Codigo:" & errorBit.IdError)
            End If
        Catch ex As Exception
            Dim errorBit = eventoBit.GuardarError("Error al crear BSO: " & ex.Message)
            Throw New Exception(ex.Message & " -Codigo:" & errorBit.IdError)
        End Try
    End Function

    Public Function CerrarBSO(ByVal fechaApertura As Date, ByRef eventoBit As CSBitEvento) As Boolean
        Dim sMsgError As String = ""
        Try
            Dim listaPS As List(Of CTPartidaSolicitud) = BSO.LstPS.FindAll(Function(x) x.EstatusActualPS = CTPartidaSolicitud.enumEstatusPS.CREADA _
                                                                               or x.EstatusActualPS = CTPartidaSolicitud.enumEstatusPS.ENVIADA _
                                                                               or x.EstatusActualPS = CTPartidaSolicitud.enumEstatusPS.LIBERADA _
                                                                               or x.EstatusActualPS = CTPartidaSolicitud.enumEstatusPS.EN_DISTRIBUCION)
            Dim listDetalleEventoBit = New List(Of CTBitEventoDet)
            For Each ps As CTPartidaSolicitud In listaPS
                listDetalleEventoBit.Add(New CTBitEventoDet("idPS", ps.PartidaSolId))
            Next
            eventoBit.GuardarDetalles(listDetalleEventoBit)
            For Each ps As CTPartidaSolicitud In listaPS
                CerrarIncompletaPS(ps, "", eventoBit)
            Next
            
            If CFLServicioLocalSQLServerDB.CerrarBSO(fechaApertura, sMsgError) = True Then
                Return True
            Else
               Dim errorBit = eventoBit.GuardarError("Error al cerrar BSO: " & sMsgError)
               Throw New Exception(sMsgError & " -Codigo:" & errorBit.IdError)
            End If
        Catch ex As Exception
            Throw ex
        End Try
    End Function

    Public Function CrearPS(ByRef pPs As CTPartidaSolicitud) As Boolean
        Dim sMsgError As String = ""

        Try
            Dim folio As Integer = CFLServicioLocalSQLServerDB.ObtieneFolio("ID_PARTIDA_PS","FL_OP_PS")
            pPs.PartidaSolId = folio
            If CFLServicioLocalSQLServerDB.CrearPS(pPs, sMsgError) = False Then
                'And CFLServicioLocalSQLServerDB.CrearPSBSO(pPs, sMsgError) = False Then
               Throw New Exception(sMsgError)
            End If
        Catch ex As Exception
            Throw ex
        End Try
        Return True
    End Function

    Public Function ModificarPS(ByRef pPs As CTPartidaSolicitud) As Boolean
        Dim sMsgError As String = ""

        Try
            If CFLServicioLocalSQLServerDB.ModificarPS(pPs, sMsgError) = False Then
                'And CFLServicioLocalSQLServerDB.ModificarPSBSO(pPs, sMsgError) = False Then
               Throw New Exception(sMsgError)
            End If
        Catch ex As Exception
            Throw ex
        End Try
        Return True
    End Function

    Public Function CerrarPS(ByRef pPs As CTPartidaSolicitud, ByVal comentario As String) As Boolean
        Dim sMsgError As String = ""

        Try
            If CFLServicioLocalSQLServerDB.ActualizaEstatusPS(pPs.PartidaSolId, CTPartidaSolicitud.enumEstatusPS.CERRADA, comentario, sMsgError) = False Then
               Throw New Exception(sMsgError)
            End If
        Catch ex As Exception
            Throw ex
        End Try
        Return True
    End Function

    Public Function CerrarIncompletaPS(ByRef pPs As CTPartidaSolicitud, ByVal comentario As String, ByRef eventoBit As CSBitEvento) As Boolean

        Dim sMsgError As String = ""
        Dim Estatus As Integer = CTPartidaSolicitud.enumEstatusPS.CERRADA_INCOMPLETA
        If (pPs.EstatusActualPS = CTPartidaSolicitud.enumEstatusPS.LIBERADA _
            or pPs.EstatusActualPS = CTPartidaSolicitud.enumEstatusPS.CREADA _
            or pPs.EstatusActualPS = CTPartidaSolicitud.enumEstatusPS.ENVIADA) Then
            Estatus = CTPartidaSolicitud.enumEstatusPS.CANCELADA
        End If
        If (pPs.EstatusActualPS = CTPartidaSolicitud.enumEstatusPS.EN_DISTRIBUCION) Then
            Estatus = CTPartidaSolicitud.enumEstatusPS.CERRADA
            Dim dtDatos As DataTable = CFLServicioLocalSQLServerDB.IntermPorDistribuir(pPS.PartidaSolId)
            If dtDatos.Rows.Count > 0 Then
                Estatus = CTPartidaSolicitud.enumEstatusPS.CERRADA_INCOMPLETA
            End If
            dtDatos = CFLServicioLocalSQLServerDB.OrdenesSinEnvioDecalog(pPS.PartidaSolId)
            If dtDatos.Rows.Count > 0 Then
                Estatus = CTPartidaSolicitud.enumEstatusPS.CERRADA_INCOMPLETA
            End If
        End If

        Try
            If CFLServicioLocalSQLServerDB.ActualizaEstatusPS(pPs.PartidaSolId, Estatus, comentario, sMsgError) = False Then
               Dim errorBit = eventoBit.GuardarError("Error al cerrar PS - BSO: isPS: " & pPs.PartidaSolId & " Estatus: " & Estatus & " - EX: " & sMsgError)
               Throw New Exception(sMsgError & " -Codigo:" & errorBit.IdError)
            End If
        Catch ex As Exception
            Dim errorBit = eventoBit.GuardarError("Error al cerrar PS - BSO: isPS: " & pPs.PartidaSolId & " Estatus: " & Estatus & " - EX: " & ex.Message)
            Throw New Exception(ex.Message & " -Codigo:" & errorBit.IdError)
        End Try
        Return True
    End Function

    Public Function CrearPAJ(ByRef pPaj As CTPartidaAjuste) As Boolean
        Dim sMsgError As String = ""

        Try
            Dim folio As Integer = CFLServicioLocalSQLServerDB.ObtieneFolio("ID_PARTIDA_AJUSTE","FL_OP_PAJ")
            pPaj.PartidaAjusteID = folio
            If CFLServicioLocalSQLServerDB.CrearPAJ(pPaj, sMsgError) = False Then
               Throw New Exception(sMsgError)
            End If
        Catch ex As Exception
            Throw ex
        End Try
        Return True
    End Function

    Public Function ModificarPAJ(ByRef pPaj As CTPartidaAjuste) As Boolean
        Dim sMsgError As String = ""

        Try
            If CFLServicioLocalSQLServerDB.ModificarPAJ(pPaj, sMsgError) = False Then
               Throw New Exception(sMsgError)
            End If
        Catch ex As Exception
            Throw ex
        End Try
        Return True
    End Function

    Public Function RegistrarNotificacion(ByRef pMensaje As String) As Boolean
        Try
            Dim sMsgError As String = ""
            Dim pId As Integer = CFLServicioLocalSQLServerDB.ObtieneFolio("ID","FL_NOTIFICACION")
            If CFLServicioLocalSQLServerDB.RegistrarNotificacion(pId, pMensaje, sMsgError) = True Then
                Return True
            Else
               Throw New Exception(sMsgError)
            End If
        Catch ex As Exception
            Throw ex
        End Try

    End Function



      #Region "GESTIÓN DE PARTIDAS DE EJECUCIÓN"

    Public Sub CargarPartidasEjecucionEnBSO () 
      Dim dtPEJ         As DataTable
      Dim pej           As CTPartidaEJ
      Dim ps            As CTPartidaSolicitud
      Dim ancestro      As CTPartidaEJ.structAncestrosPEJ
      Dim paramInter    As CTParamIntermediario
      Dim estado        As CTEstadoPEJ




        Try
         
             dtPEJ  = CFLServicioLocalSQLServerDB.ObtenerPartidasEJPorBSOActual(BSO.BSOId)
            If Not dtPEJ is Nothing 


                For Each registro As DataRow In  dtPEJ.Rows
                    pej        = New CTPartidaEJ()
                    paramInter = New CTParamIntermediario()
                    estado     = New CTEstadoPEJ ()

                     With pej



                        paramInter.IdIntermediario      = registro("CVE_INTERMEDIARIO")
                        paramInter.NivelMaxDistrib      = registro("NIVEL_MAX_DISTRIB") 
                        paramInter.NivelMinDistrib      = registro("NIVEL_MIN_DISTRIB")
                        paramInter.NombreIntermediario  = registro("NOM_INTERMEDIARIO")

                        estado.PartidaEJ                = registro("ID_PARTIDA_EJ")
                        estado.CantidadDistribuida      = registro("CANTIDAD_DISTRIB")
                        estado.CantidadXDistrib         = registro("CANTIDAD_X_DISTRIB")
                        estado.EstatusDist              = registro("ESTATUS_DIST")
                        


                        ancestro.PSId         = registro("ID_PARTIDA_PS")
                        .PartidaEJId          = registro("ID_PARTIDA_EJ")
                        .SecPEJ               = registro("SEC_PEJ")
                        .HoraIngreso          = registro("HORA_INGRESO")
                        .HoraEjecucion        = registro("HORA_EJECUCION")
                        .Tasa                 = registro("TASA")

                        .Intermediario        = paramInter
                        
                        .CantidadAsigInterm   = registro("CANTIDAD")
                        .Medio                = registro("MEDIO")
                        .Flexible             = registro("FLEXIBLE")
                        .Observaciones        = registro("OBSERVACIONES")
                        .PEJConfirmada        = registro("PEJ_CONFIRMADA")


                        .EstatusPEJ           = estado


                         ancestro.BSOId  = BSO.BSOId
                         .AncestrosPEJ = ancestro


                    End With
                    
                    ps = BSO.LstPS.Find(Function(x) x.PartidaSolId = ancestro.PSId)
                    ps.LstPEJ.Add(pej)
                    BSO.LstPEJ.Add(pej)
            
                Next


            End If
            

        Catch ex As CError
             ex.ATRAPADO = True
             Throw ex
        End Try

    End Sub

    

    Public Function ObtenerCatalogoInterParamSel (ByRef ps As CTPartidaSolicitud ) As List(Of CTParamIntermediario)
      Dim lstInterParam  = New  list(Of CTParamIntermediario )
      Dim dt As DataTable  

      Dim interDefault  As  CTParamIntermediario = New CTParamIntermediario (0,"--------",0,0,False)
      

      Try

            If ps is Nothing then 
               dt =   CFLServicioLocalSQLServerDB.ObtenerCatalogoInterParamDB ()
            else
               dt =   CFLServicioLocalSQLServerDB.ObtenerCatalogoInterParamDB (ps.TvngId)
            End If
            




              If not dt is Nothing then 

                
                   For Each registro  In dt.Rows  

                     If registro("SELECCIONADO") = true  THEN '1 = true

                          lstInterParam.Add (New CTParamIntermediario(registro("ID_INTERMEDIARIO"), _
                                                                      registro("NOMBRE"), _
                                                                      registro("NIVEL_MAX_DISTRIB"), _
                                                                      registro("NIVEL_MIN_DISTRIB"), _
                                                                      registro("SELECCIONADO") ) _
                                             )
                    End If 

                   Next

              End If

              lstInterParam.Add (interDefault)
              
              Return lstInterParam


      Catch ex As Exception
           Throw ex         
      End Try

    End Function 
     


     







    Public Function ObtenerCatalogoInterParam () As List(Of CTParamIntermediario)
      Dim lstInterParam  = New  list(Of CTParamIntermediario )
      Dim dt As DataTable             

      Try
              dt =   CFLServicioLocalSQLServerDB.ObtenerCatalogoInterParamDB ()

              If not dt is Nothing then 

                
                   For Each registro  In dt.Rows  

                          lstInterParam.Add (New CTParamIntermediario(registro("ID_INTERMEDIARIO"), _
                                                                      registro("NOMBRE"), _
                                                                      registro("NIVEL_MAX_DISTRIB"), _
                                                                      registro("NIVEL_MIN_DISTRIB"), _
                                                                      registro("SELECCIONADO")) _
                                             )
                   Next

              End If

              
              Return lstInterParam

      Catch ex As Exception
           Throw ex         
      End Try


    End Function 




    #End Region
    



    Public Shared  Function  ConvertirAFecha(ByVal sFecha As String) As Date

    Dim dia As Integer
    Dim mes As Integer
    Dim ano As Integer
    
    Dim fecha As Date 


    Try

       dia  = sFecha.Substring (8,2)
       mes  = sFecha.Substring (5,2) 
       ano  = sFecha.Substring (0,4)

      fecha = New Date(ano,mes,dia)

    Catch ex As Exception
       Return Nothing 
    End Try

     Return fecha 
       
    End Function

    Public Function ObtieneDireccionMails(ByVal IdIntermediario As Integer) As List(Of CTParamCartaEnvio)
        Try
            Dim lstMails As New List(Of CTParamCartaEnvio)
            Dim dtDatos      As DataTable = CFLServicioLocalSQLServerDB.ObtieneDireccionMails(IdIntermediario)
            Dim c            As CTParamCartaEnvio

            If dtDatos.Rows.Count > 0 Then
                For Each dt As DataRow In dtDatos.Rows
                    c = New CTParamCartaEnvio()
                    c.DireccionMail = Convert.ToString(dt("DIRECCION_MAIL"))
                    lstMails.Add(c)
                    c = Nothing
                Next
            End If

            Return lstMails
        Catch ex As Exception                
            Throw ex
        End Try
    End Function

    Public Sub GuardarMails(ByVal IdIntermediario As Integer, ByRef listaMails As List(Of CTParamCartaEnvio))
        Dim sMsgError As String = ""
        If CFLServicioLocalSQLServerDB.GuardarMails(IdIntermediario, listaMails, sMsgError) = False Then
           Throw New Exception(sMsgError)
        End If
    End Sub

End Class
